<?php
class Application_Model_User extends Application_Model_DomainObject{
	
	protected $_id;
	
	protected $_email;

	protected $_nikename;
	
	protected $_realname;
	
	protected $_datecreated;
	
	protected $_password;
	
	protected $_passwordsalt;
	
    protected $_username;

    protected $_userLevel;

    protected $_lastLogin;

    protected $_synKey;

    protected $_userType;

    protected $_pic;
    
    protected $_state;
    
    protected $_logintimes;
    
    protected $_loginip;
    
    protected $_storeno;
    protected $_remark;
    /**
     * 新用户 
     */
    const STATUS_New=0;

    /**
     * 邮箱已经验证 
     */
    const STATUS_Email=1;


    public function  getPicFile(){
        if($this->_pic)
        {
                $userid=str_pad($this->_id,9,'0',STR_PAD_LEFT);
            return '/data/avatar/'.substr($userid,0,3).'/'.substr($userid,3,2).'/'.substr($userid,5,2).'/'.$this->_pic;
        }
        else {
            return '/data/avatar/00.png';
        }
    }


    public static function current(){
		return Application_Model_User::getByEmail(Uuch_BaseController::getCurrentUserName());
	}
        
    public function getLevel(){
        return $this->userLevel;
    }

        /**
	 * 生成密码
	 * @param string $password
	 * @param string $passwordSalt
	 * @return string
	 */
	public function generatePassword($password,$passwordsalt){
		return md5(md5($password).$passwordsalt);
	}
	 
	/**
	 * 根据email返回用户
	 * @param string $email
	 * @return Application_Model_User
	 */
	public static function getByEmail($email){
		$db = new Application_Model_DbTable_User();
		return $db->queryOne(array('email'=>$email));
	}
	
	public static function getByUserId($id){
		$db = new Application_Model_DbTable_User();
		return $db->queryOne(array('id'=>$id));
	}
	
        /*
         * 根据key获取用户信息
         */
        public  static function getByKey($synKey){
            $db = new Application_Model_DbTable_User();
            return $db->queryOne(array('synKey'=>$synKey));
        }

        /*
         * 获取用户总数
         */
        public static function  getItemCount(){
            $db = new Application_Model_DbTable_User();
            return $db->getItemCount();
        }

        /**
	 * 根据用户名
	 * @param string $username
	 * @return Application_Model_User
	 */
	public static function getbyusername($username){
		$db = new Application_Model_DbTable_User();
		return $db->queryOne(array('username'=>$username));
	}
        
        /**
	 * 根据用户名
	 * @param string $nikename
	 * @return Application_Model_User
	 */
	public static function getbynikename($nikename){
		$db = new Application_Model_DbTable_User();
		return $db->queryOne(array('nikename'=>$nikename));
	}


    private $_account;
    /**
     * 返回用户的帐号
     * @return Application_Model_UserAccount 
     */
    public function getAccount(){
        if($this->_account==NULL){
            $this->_account = Application_Model_UserAccount::getByUserId ($this->Id);
            if($this->_account == NULL){
                $account = new Application_Model_UserAccount(array('id'=>$this->Id,'money'=>0,'score'=>0));
                $account->insertId();
                $this->_account = $account;
            }
        }
        return $this->_account;
    }
    
    private $_profile;
    /**
     * 返回当前用户的个人信息
     * @return Application_Model_Profile 
     */
    public function getProfile(){
        if($this->_profile==NULL){
            $this->_profile =Application_Model_Profile::getByUserId($this->Id);
        }
        return $this->_profile;
    }
    
    /**
     * 返回当前用户的等级
     */
    public  function getLevelText(){
    	$levels = array('0'=>'普通会员','1'=>'铜账户','2'=>'银账户','3'=>'金账户','4'=>'白金账户');
        if($this->userLevel || $this->userLevel=='')
            $this->userLevel=0;
    	return $levels[''.$this->userLevel];
    }
    
//    /**
//     * 返回用户的仓库号
//     */
//    public function getStoreNo(){
//    	return Uuch_Util::getShortNum($this->Id, 4);
//    }
    
    private $_coupons;
    /**
     * 返回当前用户的所有可用优惠券
     * @return type 
     */
    public function getCoupons(){
        if($this->_coupons==NULL){
            $this->_coupons = Application_Model_Coupon::getByUser($this->_id,  Application_Model_Coupon::STATUS_OK);
        } 
        return $this->_coupons;
    }
    
    public static function getByStoreNo($storeno){
        return Application_Model_User::getDao()->queryOne(array('storeno'=>$storeno));
    }
    
    public static function search(){
        return self::getDao()->queryPage(array('storeno'=>'P0002'));
    }
    public static function getcountuser()
    {
        $where['datecreated >='] = date('Y-m-d');
        $result = Application_Model_User::getDao()->count($where);
        return $result;      
    }
    public static function getloginuser()
    {
        $where['lastLogin >='] = date('Y-m-d');
        $result = Application_Model_User::getDao()->count($where);
        return $result;
                
    }
     public static function getselcount($quick, $dateselect, $starttime, $endtime, $pagesize, $pageindex) 
    {
        $where = array();
        $and = '';
        if ($quick != '') {
            $and = ' ( ';
            $where[$and . ' nikename like '] = '%' . $quick . '%';
            $and = ' or ';
            $where[$and . ' email like '] = '%' . $quick . '%';
            $and = ' or ';
            $where[$and . ' storeno like '] = '%' . $quick . '%';
            $and = ' ) and ';
            $where[$and . ' 1 = '] = 1;
            $and = " and ";
        }
        if ($dateselect == 'regedit') {
            $key = ' datecreated ';
        } else if ($dateselect == 'login') {
            $key = ' lastLogin ';
        }
        if ($starttime != '') {
            $where[$and . $key . '>='] = $starttime;
            $and = ' and ';
        }
        if ($endtime != '') {
            $where[$and . $key . '<='] = $endtime;
        }
        var_dump($where);exit;
        $result = Application_Model_User::getDao()->queryPage($where,'id desc',$pagesize,$pageindex);
        return $result;
    }
    /**
     * 获取用户积分
     */
    public function getbyscore()
    {
        $userid = $this->_id;
        $where['id = '] = $userid;
        $accountDb = new Application_Model_DbTable_UserAccount();
        $result = $accountDb->queryOne($where);
        return $result;
    }
    public static function editmoney($userid,$money,$reason,$message,$operate)
    {
        $userItem = Application_Model_UserAccount::load($userid);
        if($userItem){
            $beforeMoney = $userItem->money;
            if($operate == "recharge"){ //充值
                $userItem->money = $userItem->money + $money;
                $title = "手工充值：".$money;
                $content = "于".date("Y-m-d H:i:s")." 悠奇工作人员：".Uuch_Util::decryptString($_COOKIE["__adminusername"])." 手工充值：".$money."(元)<br>原因为：".$reason;
                $re = 3;
                Application_Model_Operate::intooperate($money, Application_Model_Operate::Type_rechargeuser, $userItem->id, $userItem->id);
                if($message == "message"){
                    Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_rechargemessage, $userItem->id, $userItem->id);
                }
            }else if($operate == "deduct"){//扣款
                $userItem->money = $userItem->money - $money;
                $title = "手工扣款：".$money;
                $content = "于".date("Y-m-d H:i:s")."悠奇工作人员：".Uuch_Util::decryptString($_COOKIE["__adminusername"])."手工扣款：".$money."(元)<br>原因为：".$reason;
                $re = 4;
                Application_Model_Operate::intooperate($money, Application_Model_Operate::Type_deductuser, $userItem->id, $userItem->id);
                if($message == "message"){
                    Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_deductmessage, $userItem->id, $userItem->id);
                }
            }
            $afterMoney = $userItem->money;
            $userItem->save();
            $history = new Application_Model_UserAccountHistory();
            $history->type = 0;
            $history->beforeMoney = $beforeMoney;
            $history->afterMoney = $afterMoney;
            $history->comment = $reason ;
            $history->dateCreated = date("Y-m-d H:i:s");
            $history->relaseId = "1";
            $history->state = 10;
            $history->accountId = $userid;
            $history->save();
            if($message == "message"){
                $messageItem = new Application_Model_Mail();
                $messageItem->title = $title;
                $messageItem->userId = $userid;
                $messageItem->type = 2;
                $messageItem->status = 0;
                $messageItem->message = $content;
                $messageItem->dateCreated = date("Y-m-d H:i:s");
                $messageItem->save();
            }
            return $re;
        }else{
            return 2;
        }
    }
    //根据仓库号获取用户信息
    public static function bystore($storeno)
    {
        $where[' storeno = '] = $storeno;
        return Application_Model_User::getDao()->queryOne($where);
    }
    /*
     * 根据ip获取对应国家
     */
    public function  getbyip(){
        $ipDb = new Application_Model_ip();
        $ip = $this->_loginip;
        $result = $ipDb->convertip($ip);
        $result = iconv("GBK", "UTF-8", $result);
        return $result;
    }
    
    public function byStoreLocation()
    {
        $result = Application_Model_StoreLocation::getUserAll($this->_id);
        if(!$result){
//            $locationItem = Application_Model_StoreLocation::getDao()->queryOne(array("status"=>0));
//            if($locationItem){
//                $locationItem->userId = $this->_id;
//                $locationItem->status = 1;
//                $locationItem->save();
//                $result = Application_Model_StoreLocation::getUserAll($this->_id);
//            }else{
                return 0;
//            }
        }
        foreach ($result as $value) {
            $arrre[] = $value->locationNo;
        }
        return $arrre;
    }
     public function getUserDetail($id,$nikename=null,$storeno=null) {
        $getItem = new Application_Model_DbTable_User();
        $where['id = '] = $id;
        $and = ' and ';
        if ($nikename != '') {
            $where[$and . ' nikename like '] = '%' . $nikename . '%';
        }
        if ($storeno != '') {
            $where[$and . ' storeno like '] = '%' . $storeno . '%';
        }
        return $getItem->queryOne($where);
    }
    public function editUserDetail($id,$realname,$nikename,$uemail,$score,$profile_set)
    {
        if($id != ''){                     
            $userDetail = Application_Model_User::load($id);
            $userDetail->realname = $realname;
            $userDetail->nikename = $nikename;
            $userDetail->email = $uemail;
            $userDetail->save();
            $accountDetail = Application_Model_UserAccount::load($id);
            if($accountDetail == null){
                $accountDetail = new Application_Model_UserAccount();
            }
            $accountDetail->score = (int)$score;
            $accountDetail->save();
            
            $profileDetail=Application_Model_Profile::getByUserId($id);
            if($profileDetail == null){
                $profileDetail = new Application_Model_Profile();
            }
            $profileDetail->userId = $id;
                foreach ($profile_set as $key => $v){
                    $profileDetail->$key = $v;
                }
            Application_Model_Operate::intooperate(0, Application_Model_Operate::Type_edituser, $id, $id);
            $profileDetail->save();
            return true;
        }else{
            return false;
        }
    }
}